package cn.tl.user.service.impl;

import cn.tl.base.constants.WxConstants;
import cn.tl.base.exception.BusinessException;
import cn.tl.org.utils.AjaxResult;
import cn.tl.user.domain.LoginInfo;
import cn.tl.user.domain.User;
import cn.tl.user.domain.WxUser;
import cn.tl.user.mapper.LoginInfoMapper;
import cn.tl.user.mapper.UserMapper;
import cn.tl.user.mapper.WxUserMapper;
import cn.tl.user.service.IWxUserService;
import cn.tl.utils.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WxUserServiceImpl implements IWxUserService {
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult wxLogin(Map<String, String> map) {
        //获取access_token
        String code = map.get("code");
        //获取请求
        String url= WxConstants.ACCESS_TOKEN_URL
                .replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        String result = HttpClientUtils.httpGet(url);
        System.out.println(result);
        //格式化json
        JSONObject jsonObject = JSON.parseObject(result);
        //取值
        /*     {
              接口调用凭证:"access_token": "ACCESS_TOKEN",
              有效期:"expires_in": 7200,
              刷新有效期:"refresh_token": "REFRESH_TOKEN",
              授权用户唯一标识:"openid": "OPENID",
              "scope": "SCOPE",
              授权标识:"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
               }
        */
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        System.out.println(access_token);

        WxUser wxUser = wxUserMapper.loadByOpenId(openid);
        System.out.println("唯一标识"+ openid);
        if(wxUser!=null){//老用户
            //微信关联用户
            User user = userMapper.findById(wxUser.getUser_id());
            //用户关联登录
            LoginInfo loginInfo = loginInfoMapper.findById(user.getLogininfo_id());
            return noPwdLogin(loginInfo);
        }else {//新用户
            String redirectUri="/binder.html?access_token="+access_token+"&openid="+openid;
            return AjaxResult.me().setSuccess(false).setResultObj(redirectUri);
        }


    }

    @Override
    public AjaxResult bind(Map<String, String> map) {
        String phone = map.get("phone");
        String codeType = map.get("codeType");
        String code = map.get("code");
        String access_token = map.get("access_token");
        String openid = map.get("openid");



        //验证验证码是否正确
        String codeInredis = (String) redisTemplate.opsForValue().get(phone+":"+codeType);
        //取验证码
        if(codeInredis==null){
           return AjaxResult.me().setMessage("验证码错误");
        };
        if (!codeInredis.split(":")[0].equals(code)){
            return AjaxResult.me().setMessage("验证码错误");
        }
        //获取个人信息
        String url=WxConstants.WXUSER_INFO
                .replace("ACCESS_TOKEN",access_token)
                .replace("OPENID",openid);

        String result = HttpClientUtils.httpGet(url);
        /*
            {
              "openid": "OPENID",
              "nickname": "NICKNAME",
              "sex": 1,
              "province": "PROVINCE",
              "city": "CITY",
              "country": "COUNTRY",
              "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
              "privilege": ["PRIVILEGE1", "PRIVILEGE2"],
              "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
            }

        */
        JSONObject jsonObject = JSON.parseObject(result);
        //生成微信用户
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        //根据手机号查询用户是否注册过
        User user = userMapper.findByPhone(phone);
        LoginInfo loginInfo=null;
        if (user==null){
            user=new User();
            user.setUsername(jsonObject.getString("openid"));
            user.setPhone(phone);
            user.setCreatetime(new Date());
            user.setState(1);
            user.setHeadImg(jsonObject.getString("headimgurl"));

            loginInfo=new LoginInfo();
            BeanUtils.copyProperties(user,loginInfo);
            loginInfo.setType(1);
            loginInfo.setDisable(1);
            loginInfoMapper.save(loginInfo);
            user.setLogininfo_id(loginInfo.getId());
            userMapper.save(user);

        }else {
            loginInfo = loginInfoMapper.findById(user.getLogininfo_id());
        }
        //把用户和wxUser绑定
        wxUser.setUser_id(user.getId());
        //保存WxUser
        wxUserMapper.save(wxUser);
        //免密登录
        return noPwdLogin(loginInfo);

    }

    //免密登录
    private AjaxResult noPwdLogin(LoginInfo loginInfo) {
        //生成token
        String token = UUID.randomUUID().toString();
        //放入redis里面
        redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        loginInfo.setPassword("");
        loginInfo.setSalt("");
        map.put("loginInfo",loginInfo);
        return AjaxResult.me().setResultObj(map);
    }
}
